import 'package:flutter/material.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:audio_recorder/audio_recorder.dart';
import '../utils/http_utils.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:permission_handler/permission_handler.dart';
import 'package:file/local.dart';
class AudioRec{
  String _authInfo;
  Future<String> start(BuildContext context) async {
   // try {
    await requestPermission();
      if (await AudioRecorder.hasPermissions) {
            Directory appDocDirectory =
            await getApplicationDocumentsDirectory();
            String path = appDocDirectory.path + '/' + timestamp()+".wav";
          print("Start recording: $path");
          await AudioRecorder.start(
              path: path, audioOutputFormat: AudioOutputFormat.WAV);
          return path;
      } else {
        Scaffold.of(context).showSnackBar(
            new SnackBar(content: new Text("You must accept permissions")));
      }
//    } catch (e) {
//      print(e);
//    }
    return "error";
  }

  Future<String> stop() async {
    var recording = await AudioRecorder.stop();
    print("Stop recording: ${recording.path}");
    //getTextFromFile(recording.path);
    File file = LocalFileSystem().file(recording.path);
    int len=await file.length();
    print("length:$len");
    List<int> bytes=await file.readAsBytes();
//    HttpUtils().upload("http://192.168.1.213:8080/app/receiveLog",
//        baseFormData: BaseFormData().addFile(
//            "recFile", BaseFile(File(recording.path), fileName: "rec.wav")));
    return base64.encode(bytes);
  }

  getTextFromFile(path) async{
    File file = File(path);
    List<int> bytes=await file.readAsBytes();
    int len=await file.length();
    String base64str=base64.encode(bytes);
    print("  File length: $len");
    print("  File length: $bytes");
    print("  File base64: $base64str");
    await getAuth().then((token){
      getRadioInfo(token,base64str,len).then((resp){
        print("resp:$resp");
        print(resp.data["result"]);
        HttpUtils().upload("http://192.168.1.150:8080/app/receiveLog",
            baseFormData: BaseFormData().addFile(
                "logFile", BaseFile(File(path), fileName: "rec.wav")));
      });
    });

  }
  Future<bool> isRecording() async{
    bool isRecording = await AudioRecorder.isRecording;
    return isRecording;
  }

  String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();

  //获取access_token
  Future<String> getAuth() async{
    if(_authInfo!=null) return Future.value(_authInfo);
    String ak='ozt0wf9Un27lGz5XdSXzQpdk';
    String sk='oGMj53TgeI0t68hIAw5cOHq0CzgUPS1E';
    // 获取token地址
    String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
    String getAccessTokenUrl = authHost
        // 1. grant_type为固定参数
        + "grant_type=client_credentials"
        // 2. 官网获取的 API Key
        + "&client_id=" + ak
        // 3. 官网获取的 Secret Key
        + "&client_secret=" + sk;

    BaseResp resp= await HttpUtils().post(getAccessTokenUrl);
    _authInfo=resp.data['access_token'];
    return resp.data['access_token'];

  }
  //语音信息
  Future<BaseResp> getRadioInfo(String accessToken,String base64Str,int len) async{
    String url='https://vop.baidu.com/pro_api';
    Map data={"format":"wav","rate":16000,"dev_pid":80001,"channel":1,"token":accessToken,"cuid":"wondersgroup_zhrs","len":len,"speech":base64Str};
    Options options=Options();
    options.contentType=ContentType.json;
    return await HttpUtils().post(url,
        data: data,
        options: options
    );
  }
  Future requestPermission() async {
    // 申请权限
    Map<PermissionGroup, PermissionStatus> permissions =
    await PermissionHandler().requestPermissions([PermissionGroup.storage,PermissionGroup.speech,PermissionGroup.microphone]);
    // 申请结果
    PermissionStatus permission =
    await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
    if (permission == PermissionStatus.granted) {
      print( "storage权限申请通过");
    } else {
      print( "storage权限申请被拒绝");
    }
  }
}